// import readFiles from '../../src/router/create/resolvePagePath'
import { fileURLToPath } from 'node:url'
import path, { dirname } from 'node:path'
import fs from 'node:fs'

const routerMap = []

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
async function writeMain(routes) {
  const parents = []
  function resolvePath(item, parent?) {
    const path = item.path
    if (!path) {
      return
    }
    const current: any = {
      name: item.meta.title,
    }
    if (parent) {
      current.path = `${parent.path}/${item.path}`
      parent.children.push(current)
    }
    else {
      current.path = item.path
      parents.push(current)
    }
    current.children = []
    if (item.children) {
      item.children.forEach((child) => {
        resolvePath(child, current)
      })
    }
    else {
      delete current.children
    }
  }

  routes.forEach((item) => {
    resolvePath(item)
  })

  const pathValue = { data: parents }
  fs.writeFileSync(path.join(__dirname, '../../dist/pagePath.json'), JSON.stringify(pathValue, null, 3))
  // eslint-disable-next-line no-console
  console.log('dist/pagePath.json - 路由文件生成成功')
}

export default function resolvePath(): any {
  return {
    name: 'generate-route-file',
    apply: 'build',
    transform(code, id) {
      if (id.includes('/src/router/modules')) {
        // 写一个正则匹配内衣的文本内容
        const newCode = code.replace(/import\((.*?)\)/g, '{}').replace('export default routes;', 'return routes')
        // eslint-disable-next-line
        const fn = new Function(newCode)
        routerMap.push(fn())
      }
      return code
    },
    writeBundle() {
      writeMain(routerMap)
    },
  }
}
